import React, { useState, useRef, useEffect } from 'react';
import { View, FlatList, StyleSheet, KeyboardAvoidingView, Platform, SafeAreaView } from 'react-native';
import { ChatMessage, ChatMessageProps } from './ChatMessage';
import { MultimodalInput } from '../multimodal/MultimodalInput';
import theme from '../../styles/theme';
import { MultimodalInput as MultimodalInputType } from '../../../api/interfaces/qwen';

interface ChatScreenProps {
    contextId?: string;
    onSendMessage: (input: MultimodalInputType) => Promise<void>;
    onCancelRequest?: () => void;
    isProcessing?: boolean;
}

export const ChatScreen: React.FC<ChatScreenProps> = ({
    contextId,
    onSendMessage,
    onCancelRequest,
    isProcessing = false
}) => {
    const [messages, setMessages] = useState<ChatMessageProps[]>([]);
    const [loadingMessage, setLoadingMessage] = useState<ChatMessageProps | null>(null);
    const flatListRef = useRef<FlatList>(null);

    // 当消息列表更新时滚动到底部
    useEffect(() => {
        if (flatListRef.current && messages.length > 0) {
            setTimeout(() => {
                flatListRef.current?.scrollToEnd({ animated: true });
            }, 100);
        }
    }, [messages, loadingMessage]);

    // 处理发送消息
    const handleSendMessage = async (input: MultimodalInputType) => {
        const userMessage: ChatMessageProps = {
            id: Date.now().toString(),
            role: 'user',
            content: input.text || '',
            images: input.images || [],
            timestamp: new Date()
        };

        // 添加用户消息
        setMessages(prevMessages => [...prevMessages, userMessage]);

        // 创建一个加载中的助手消息
        const pendingAssistantMessage: ChatMessageProps = {
            id: (Date.now() + 1).toString(),
            role: 'assistant',
            content: '',
            timestamp: new Date(),
            isLoading: true
        };

        setLoadingMessage(pendingAssistantMessage);

        try {
            // 调用API发送消息
            await onSendMessage(input);

            // 模拟助手回复（实际应用中，这部分会由API响应处理）
            // TODO: 在实际集成时，这部分将被异步事件处理
        } catch (error) {
            // 处理错误，标记消息为失败状态
            setLoadingMessage(prev =>
                prev ? { ...prev, isLoading: false, isError: true } : null
            );
        }
    };

    // 处理API回复
    const handleApiResponse = (content: string) => {
        if (loadingMessage) {
            const assistantMessage: ChatMessageProps = {
                ...loadingMessage,
                content,
                isLoading: false
            };

            setLoadingMessage(null);
            setMessages(prevMessages => [...prevMessages, assistantMessage]);
        }
    };

    // 处理重试失败的消息
    const handleRetry = (messageId: string) => {
        const messageToRetry = messages.find(msg => msg.id === messageId);
        if (messageToRetry && messageToRetry.role === 'user') {
            // 准备重新发送的输入
            const input: MultimodalInputType = {
                text: messageToRetry.content,
                images: messageToRetry.images
            };

            // 移除之前的助手回复（如果有）
            const userMessageIndex = messages.findIndex(msg => msg.id === messageId);
            if (userMessageIndex !== -1 && userMessageIndex < messages.length - 1) {
                setMessages(prevMessages => prevMessages.filter((_, index) => index !== userMessageIndex + 1));
            }

            // 重新发送消息
            handleSendMessage(input);
        }
    };

    // 渲染消息项
    const renderItem = ({ item }: { item: ChatMessageProps }) => (
        <ChatMessage
            {...item}
            onRetry={() => handleRetry(item.id)}
            onImagePress={(url) => console.log('Image pressed:', url)}
        />
    );

    return (
        <SafeAreaView style={styles.container}>
            <KeyboardAvoidingView
                style={styles.keyboardAvoidingView}
                behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
            >
                <FlatList
                    ref={flatListRef}
                    data={loadingMessage ? [...messages, loadingMessage] : messages}
                    renderItem={renderItem}
                    keyExtractor={item => item.id}
                    contentContainerStyle={styles.messagesContainer}
                />

                <View style={styles.inputContainer}>
                    <MultimodalInput
                        onSubmit={handleSendMessage}
                        disabled={isProcessing}
                        loading={isProcessing}
                        placeholder="发送消息..."
                        submitButtonText="发送"
                        allowedMedia={['image']}
                        contextId={contextId}
                    />
                </View>
            </KeyboardAvoidingView>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.background.default,
    },
    keyboardAvoidingView: {
        flex: 1,
    },
    messagesContainer: {
        padding: theme.spacing.md,
        paddingBottom: theme.spacing.lg,
    },
    inputContainer: {
        borderTopWidth: 1,
        borderTopColor: theme.colors.divider,
        padding: theme.spacing.sm,
        backgroundColor: theme.colors.background.paper,
    }
}); 